package com.tuling.member;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.tuling.NodeInfo;
import com.tuling.NodeStatus;
import com.tuling.ZookeeperRegister;

/**
 * 会员中心系统
 * @author wangningbo
 *
 */
public class MemberServer implements Watcher{
	
	private static Logger log = LoggerFactory.getLogger(MemberServer.class);
	
	private ZookeeperRegister register = new ZookeeperRegister();
	
	private String node ;
	
	public String getNode() {
		return node;
	}

	public void setNode(String node) {
		this.node = node;
	}

	public MemberServer(String node){
		this.node = node;
	}
	
	public void regist(String serverInfo){
		ZooKeeper zk = register.getConnection(this);
		//ACL-->OPEN_ACL_UNSAFE  任何权限
		try {
			String result = zk.create(ZookeeperRegister.ROOT+"/"+node, serverInfo.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
			
			System.out.println("create Node result:"+result);
			log.info("创建节点成功,节点路径：{}", result);
			NodeInfo nodeInfo = JSON.parseObject(serverInfo, NodeInfo.class);
			String childNode = result.replaceAll(ZookeeperRegister.ROOT+"/", "");
			//System.out.println("childNode : "+childNode);
			nodeInfo.setNode(childNode);
			zk.setData(result, JSON.toJSONString(nodeInfo).getBytes(), -1);
			
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 实现zookeeper watcher监听
	 */
	public void process(WatchedEvent event) {
		
	}
	
	public static void main(String[] args) {
		MemberServer server = new MemberServer("memberserver");
		
		NodeInfo node = new NodeInfo();
		node.setClientName(null);
		node.setStatus(NodeStatus.INIT); //初始化状态
		node.setIp("120.27.193.222");
		node.setServerName(server.getNode());
		node.setPort("8080");
		node.setNum(0);
		node.setNode(server.getNode());
		
		server.regist(JSON.toJSONString(node));
		
		log.info("会员系统启动!");
		
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
